package cn.ac.cintcm.prespring.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;


/**
 * id与对应的名称索引
 * @author 何前锋 Franklin He(franklinheqf@gmail.com)
 *
 */
public class NameIndex {
    
    HashMap<Integer, String> idName;
    public NameIndex(String fileName) throws IOException {
        List<String> list = FileUtil.read(fileName);
        idName = parseLine(list);
    }
    
    public NameIndex() {
        idName = new HashMap<Integer, String>();
    }
    
    public NameIndex(List<String> strings) {
        idName = parseLine(strings);
    }
    
    public NameIndex(HashMap<Integer, String> idnames) {
        this.idName = idnames;
    }
    
    private HashMap<Integer, String> parseLine(List<String> list) {
        HashMap<Integer, String> map = null;
        if (list != null) {
            map = new HashMap<Integer, String>();
            for (String s : list) {
                if (s != null) {
                    String[] p = s.split(Config.FIELD_SPLITTER);
                    if (p != null && p.length == 2) {
                        map.put(Integer.parseInt(p[0]), p[1]);
                    }
                }
            }
        }
        return map;
    }

    public HashMap<Integer, String> getIdName() {
        return idName;
    }
    
    public String getName(Integer id) {
        return idName.get(id);
    }
    
    public void addIdName(Integer id, String name) {
        idName.put(id, name);
    }

    public void setIdName(HashMap<Integer, String> idName) {
        this.idName = idName;
    }
}
